import { createPersistedStore } from '../services/store.service';
import { TranslatorService } from '../services/translator.service';

export interface Translation {
  id: string;
  sourceText: string;
  translatedText: string;
  timestamp: number;
  sourceLanguage: string;
  targetLanguage: string;
}

interface TranslatorState {
  translations: Translation[];
  isLoading: boolean;
  error: string | null;
  
  // Actions
  translate: (text: string, from: string, to: string, autoPlay?: boolean) => Promise<void>;
  clearTranslations: () => void;
}

export const useTranslatorStore = createPersistedStore<TranslatorState>(
  {
    name: 'translator-store',
    initialState: {
      translations: [],
      isLoading: false,
      error: null,
    },
    onRehydrate: (state) => {
      console.log('Translator store rehydrated:', state);
    },
  },
  (set, get) => ({
    translate: async (text, from, to, autoPlay = false) => {
      if (!text.trim()) return;

      set({ isLoading: true, error: null });

      try {
        const { translation, detected_language } = await TranslatorService.translate(
          text,
          from,
          to
        );
        
        const newTranslation = {
          id: Date.now().toString(),
          sourceText: text,
          translatedText: translation,
          timestamp: Date.now(),
          sourceLanguage: from === 'auto' ? detected_language : from,
          targetLanguage: to,
        };

        set(state => ({
          translations: [...state.translations, newTranslation],
          isLoading: false,
        }));

        if (autoPlay) {
          await TranslatorService.textToSpeech(translation, to);
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '翻译失败，请稍后重试';
        set({ 
          error: errorMessage,
          isLoading: false,
        });
      }
    },

    clearTranslations: () => set({ translations: [] }),
  })
);